#include <iostream>
#include <cstring>
#include <unistd.h>
#include "err.hpp"
#include "log.hpp"
#include <cerrno>
#include <sys/epoll.h>
using namespace std;
static const int defaultsize = 128;
class Epoller
{
public:
    Epoller()
    {
    }
    void Create()
    {
        _efd = epoll_create(defaultsize);
        if (_efd < 0)
        {
            LogMessage(Fatal, "epoll create fail....errno:%d,errorstring:%s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERROR);
        }
    }

    int Efd()
    {
        return _efd;
    }

    bool AddModEvent(int fd,int events,int op)
    {
        struct epoll_event Events;
        Events.events=events;
        Events.data.fd=fd; //用户数据, epoll底层不对该数据做任何修改，就是为了给未来就绪返回的！
        int n=epoll_ctl(_efd,op,fd,&Events);
        if(n<0)
        {
            LogMessage(Fatal,"epoll addevent fail...errno:%d,errorstring:%s",errno,strerror(errno));
            return false;
        }
        return true;
    }

    int Wait(struct epoll_event* events,int max,int timeout )
    {
        return epoll_wait(_efd,events,max,timeout); 
    }

    bool DelEvent(int fd)
    {
        // epoll在操作fd的时候，有一个要求，fd必须合法！
        return epoll_ctl(_efd,EPOLL_CTL_DEL,fd,nullptr)==0;

    }

    ~Epoller()
    {
        close(_efd);
    }

private:
    int _efd;
};